$(function () {
    $.ajaxSetup({
        type: "post",
        dataType: "json"
    });

    var provMap = [
        //[0, "公共"],
        //[1, "北京"],
        //[2, "山东"],
        //[3, "河北"],
        //[4, "江苏"]
    ];
    var provid = 0;
    var begin = 0;
    var limit = 20;
    var fetching = false;
    var normalTopicTemplate = _.template($("#topic-manage-template").html());

    function initProv() {
        var $prov_select = $(".prov-id");
        $prov_select.empty().html("<option>正在加载信息</option>");

        var url = "/api/prov/list";
        var data = {
            postData: JSON.stringify({
                idx: 0,
                params:{}
            })
        };
        $.ajax({
            url: url,
            data: data,
            success: function(res) {
                if(res.ret == 0) {
                    provMap = res.res;
                    $prov_select.empty();
                    for (var i in provMap) {
                        var tmp = provMap[i];
                        var cont = '<option value="' + tmp['provid'] + '">' + tmp['cname'] + '</option>';
                        $prov_select.append(cont);
                    }
                }
            }
        });
    }

    initProv();

    $("#show-provid").on("change", function() {
        provid = $(this).val();
        begin = 0;
        fetching = false;
        renderNormalTopic();
    });

    $("body").on("click", ".show-img", function (e) {
        e.preventDefault();

        var indexImg = $(this).closest(".t-panel").find(".index-img");
        var imgbox = indexImg.parent();

        if(imgbox.is(":hidden")) {
            indexImg.attr("src", indexImg.attr('data-src'));
            imgbox.show();

            $(this).html('隐藏图片<span class="up-triangle"></span>');
        } else {
            $(this).html('显示图片<span class="down-triangle"></span>');
            imgbox.hide();
        }
    });

    function renderNormalTopic() {
        if (fetching) {
            return;
        }
        fetching = true;

        var normalTopicUrl = '/api/topic/list';
        var normalTopicData = {
            postData: JSON.stringify({
                idx: 0,
                params: {
                    begin: begin,
                    limit: limit,
                    provid: parseInt(provid)
                }
            })
        };

        $.ajax({
            url: normalTopicUrl,
            type: 'post',
            dataType: 'json',
            data: normalTopicData,
            success: function (res) {
                if (res.ret == 0) {
                    var topicElem = $(".show-container");
                    if (begin == 0) {
                        topicElem.empty();
                    }
                    $.each(res.res, function (idx, normalTopic) {
                        topicElem.append(normalTopicTemplate(normalTopic));
                    });
                    begin += limit;
                }
            },
            error: function (res) {
                console.log(res.msg)
            },
            complete: function () {
                fetching = false;
            }
        });
    }

    renderNormalTopic();

    // Change this to the location of your server-side upload handler:
    var uploadUrl = '/cms/topic';
    Dropzone.autoDiscover = false;
    // Now that the DOM is fully loaded, create the dropzone, and setup the
    // event listeners
    var drop_settings = {
        maxFiles: 1,
        uploadMultiple: false,
        url: uploadUrl,
        acceptedFiles: "image/*",
        paramName: "file",
        dictDefaultMessage: "",
        dictFallbackMessage: "你的浏览器不支持拖放上传",
        autoProcessQueue: false,
        addRemoveLinks: true,
        dictRemoveFile: ""
    };
    var dz = new Dropzone(".dropzone", drop_settings);
    dz.on("sending", function (file, xhr, formData) {
        formData.append("provid", $("#new-topic-location").val());
        formData.append("title", $("#new-topic-title").val().trim());
        formData.append("summary", $("#new-topic-content").val().trim());
    });
    dz.on('success', function (file, response) {
        window.location.reload();
    });

    $(".nt-submit").on("click", function (e) {
        e.preventDefault();

        var title = $("#new-topic-title").val().trim();
        if (!title) {
            alert("标题不能为空");
            return;
        }
        dz.processQueue();
    });

    $(".more-topic").on("click", function(e) {
        e.preventDefault();

        renderNormalTopic();
    });
});